const router = require('koa-router')()
const utlis = require('../utlis/common')
const { leave } = require('../models/leaveSchema')
const { deptScema } = require('../models/deptSchema')
router.prefix('/leaves')

//查询申请列表
router.get('/leaveList', async ctx => {
    const { applyState, type } = ctx.request.query;
    let { page, skipIndex } = utlis.pager(ctx.request.query)
    let authorization = ctx.request.headers.authorization;
    let { data } = utlis.decoded(authorization)
    try {
        let params = {}
        if (type == 'approve') {
            if (applyState == 1 || applyState ==2) {
                params.curAuditUserName = data.usename;
                params.$or=[{applyState:1},{applyState:2}]
            } else if (applyState > 2) {
                params = { "auditFlows.userId": data.userid, applyState }
            } else {
                params = { "auditFlows.userId": data.userid }
            }
        } else {
            params = {
                "applyUser.userId": data.userid
            }
        if (applyState) params.applyState = applyState;

        }

        const query = leave.find(params)
        const list = await query.skip(skipIndex).limit(page.pageSize)
        const total = await leave.countDocuments(params)
        ctx.body = utlis.success({
            page: {
                ...page,
                total
            },
            data: list
        })

    } catch (error) {
        ctx.body = utlis.fail(`查询失败:${error.stack}`)
    }
})

// 申请创建
router.post("/operate", async ctx => {
    const { _id, action, ...params } = ctx.request.body
    let authorization = ctx.request.headers.authorization;
    let { data } = utlis.decoded(authorization)
    if (action == 'create') {
        //生成申请清单
        let orderNo = 'XJ'
        orderNo += new Date().getTime()
        const total = await leave.countDocuments()
        params.orderNo = orderNo + total
        //获取用户当前部门id
        let id = data.deptId
        //查找负责人信息
        let dept = await deptScema.findById(id)
        //获取人事部门和财政部门负责人的信息
        let userList = await deptScema.find({ deptName: { $in: ['人事部', "技术部"] } })
        let auditUsers = dept.userName;
        let auditFluws = [
            { userId: dept.userId, userName: dept.userName, userEmail: dept.userEmail }
        ]

        userList.map(item => {
            auditFluws.push({
                userId: item.userId, userName: item.userName, userEmail: item.userEmail
            })
            auditUsers += ',' + item.userName
        })
        //审批日志
        params.auditUsers = auditUsers
        params.curAuditUserName = dept.userName
        params.auditFluws = auditFluws
        params.auditLogs = []
        params.applyUser = {
            userId: data.userid,
            userName: data.usename,
            userEmail: data.userEmail
        }
        let res = await leave.create(params)
        ctx.body = utlis.success("", "创建成功")
    } else {
        let res = await leave.findByIdAndUpdate(_id, { applyState: 5 })
        ctx.body = utlis.success('', "操作成功")
    }
})

router.post("/approve", async ctx => {
    const { action, remak, _id } = ctx.request.body
    let authorization = ctx.request.headers.authorization;
    let { data } = utlis.decoded(authorization)
    let params = {}
    //1.待审批 2.审批中 3.审批拒绝 4.审批通过 5，作废
    try {
        let doc = await leave.findById(_id)
        let auditLogs = doc.auditLogs || []
        if (action == 'refuse') {
            params.applyState = 3
        } else {
           
            //审批通过
            if(doc.auditFluws.length ==doc.auditLogs.length){
             ctx.body=utlis.success('当前申请已处理，请勿重复提交')
            }else if(doc.auditFluws.length == doc.auditLogs.length +1){
                params.applyState = 4
            }else if(doc.auditFluws.length >doc.auditLogs.length){
                params.applyState = 2
                params.curAuditUserName =doc.auditFluws[doc.auditLogs.length+1].userName
            }

        }
        auditLogs.push({
            userId: data.userid,
            userName: data.usename,
            createTime: new Date(),
            remak,
            action: action == 'reffuse' ? '审批拒绝' : '审批通过'
        })
        params.auditLogs = auditLogs;
        let res = await leave.findByIdAndUpdate(_id, params)
        ctx.body = utlis.success("", "处理成功")
    } catch (error) {
        ctx.body = utlis.fail(`审批异常${error.message}`)
    }

})

router.get('/count',async ctx=>{
    let authorization =ctx.request.headers.authorization
    let {data} =utlis.decoded(authorization)
    try {
        let params ={}
        params.curAuditUserName = data.usename;
        params.$or=[{applyState:1},{applyState:2}]
        const total = await leave.countDocuments(params)
        ctx.body=utlis.success(total)
    } catch (error) {
        ctx.body=utlis.fail(`查询异常:${error.message}`)
    }
})


module.exports = router